package com.tony.engine;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletResponse;

public class MessageSender extends Thread {
    private final ServletResponse connection;

    public MessageSender(ServletResponse connection) {
        this.connection = connection;
    }

    @Override
    public void run() {
        try {
            while (true) {
                if (connection == null) {
                    synchronized (this) {
                        wait();
                    }
                }
                OutputStream out = connection.getOutputStream();
                out.write(getString().getBytes("utf-8"));
                out.flush();
                connection.flushBuffer();
                Thread.sleep(1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("deprecation")
    private String getString() {
        return "开始哦！" + Thread.currentThread() + " CurrentTime Go" + new Date().toLocaleString()
               + "\n";
    }
}
